import os
import time

from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from django.http import StreamingHttpResponse
from django.conf import settings
from .utils import synthesis_spoofing_detection, replay_spoofing_detection


def index(request):
    return replay(request)


def replay(request):
    res = {"upload_status": "failed", "score": "0", "audio_type": "伪造语音", "title": "重放语音检测"}
    if request.method == 'POST':
        file_name = str(request.FILES.get("file", None))

        f = request.FILES['file']

        save_dir = os.path.join(settings.MEDIA_ROOT, "replay")
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)
        timestamp = str(int(time.time()))
        file_path = os.path.join(save_dir, timestamp + "_" + file_name)
        with open(file_path, 'wb+') as destination:
            for chunk in f.chunks():
                destination.write(chunk)

        # 转换为16k-16bit音频
        wav_file = file_path + '.wav'
        cmd = f'ffmpeg -i "{file_path}" -vn -ar 16000 -ab 16 -ac 1 -acodec pcm_alaw -f wav "{wav_file}"'
        if os.system(cmd) == 0:
            score, audio_type = replay_spoofing_detection(wav_file)
        else:
            os.remove(file_path)
            score = -1
            audio_type = '不支持的文件类型'

        res["upload_status"] = "success"
        res["score"] = score
        res["audio_type"] = audio_type
        res["file_path"] = 'media/' + os.path.relpath(file_path, settings.MEDIA_ROOT)
        return JsonResponse(res)

    return render(request, "detector.html", res)


def synthesis(request):
    res = {"upload_status": "failed", "score": "0", "audio_type": "伪造语音", "title": "合成语音检测"}
    if request.method == 'POST':
        file_name = str(request.FILES.get("file", None))

        f = request.FILES['file']
        save_dir = os.path.join(settings.MEDIA_ROOT, "synthesis")
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)
        timestamp = str(int(time.time()))
        file_path = os.path.join(save_dir, timestamp + "_" + file_name)

        with open(file_path, 'wb+') as destination:
            for chunk in f.chunks():
                destination.write(chunk)

        # 转换为16k-16bit音频
        wav_file = file_path + '.wav'
        cmd = f'ffmpeg -i "{file_path}" -vn -ar 16000 -ab 16 -ac 1 -acodec pcm_alaw -f wav "{wav_file}"'
        if os.system(cmd) == 0:
            score, audio_type = synthesis_spoofing_detection(wav_file)
        else:
            os.remove(file_path)
            score = -1
            audio_type = '不支持的文件类型'

        res["upload_status"] = "success"
        res["score"] = score
        res["audio_type"] = audio_type
        res["file_path"] = 'media/' + os.path.relpath(file_path, settings.MEDIA_ROOT)
        return JsonResponse(res)

    return render(request, "detector.html", res)
